/**
 * @BelongsPackage: utils
 * @Author: wangx
 * @CreateTime: 2024-03-12  10:27
 * @Description: dto转实体工具类
 * @Version: 1.0
 */
package com.wx.subject.infra.basic.utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class MyUtils<T> extends CenterManager<T> {
    private static final Map<Class<?>, Field[]> FIELD_CACHE = new HashMap<>();
    private static MyUtils instance;
    private MyUtils() {
    }
    public static MyUtils getInstance() {
        //双检锁
        if (instance == null) {
            synchronized (MyUtils.class) {
                if (instance == null) {
                    instance = new MyUtils();
                }
            }
        }
        return instance;
    }
    public static <T> T Dto2Entity(Object entity, Class<T> clazz) {
        return (T) getInstance().DtoToEntity(entity, clazz);
    }
    /**
     * dto转实体-需要字段一致
     * @param dto
     * @param clazz
     * @return
     * @param <T>
     */
    @Override
    public   <T> T DtoToEntity(Object  dto,Class<T>  clazz) {
        if (dto == null) {
            return null;
        }
        // 获取DTO和Entity的字段
        Field[] dtoFields = getDeclaredFields(dto.getClass());
        Field[] entityFields = getDeclaredFields(clazz);

        T entity;
        try {
            entity = clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("创建失败 " + clazz.getName(), e);
        }

        // 遍历DTO字段并尝试复制到Entity
        for (Field dtoField : dtoFields) {
            for (Field entityField : entityFields) {
                if (dtoField.getName().equals(entityField.getName())) {
                    try {
                        // 类型检查和转换（如果需要）
                        if (dtoField.getType().isAssignableFrom(entityField.getType())) {
                            dtoField.setAccessible(true);
                            Object value = dtoField.get(dto);
                            entityField.setAccessible(true);
                            entityField.set(entity, value);
                        } else {
                            // 处理类型转换或记录警告/错误
                            System.out.println("类型不匹配：" + dtoField.getName() + " - " + entityField.getName());
                        }
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException("复制失败", e);
                    }
                    break; // 找到匹配的字段后跳出内层循环
                }
            }
        }

        return entity;
    }
    private static Field[] getDeclaredFields(Class<?> clazz) {
        Field[] fields = FIELD_CACHE.get(clazz);
        if (fields == null) {
            fields = clazz.getDeclaredFields();
            FIELD_CACHE.put(clazz, fields); // 缓存字段数组
        }
        return fields;
    }
}